package rinpu.springtest.config.security.Filter;

import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import rinpu.springtest.pojo.entity.SecurityUser;
import rinpu.springtest.service.web.TokenService;
import rinpu.springtest.utils.StringUtils;

import java.io.IOException;

/**
 * @Author Rin_pu
 * @Date 2025/9/19 20:59
 * @Description JwtAuthenticationTokenFilter
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        SecurityUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // todo 添加刷新
            tokenService.verifyToken(loginUser);
            // 将用户安全信息存入SecurityContextHolder, 之后SpringSecurity的过滤器就不会拦截了
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
